//
//  ChatConversationViewController.m
//  EasyChat
//
//  Created by romana on 16/6/17.
//  Copyright © 2016年 dllo. All rights reserved.
//


/*
 
 *********此页面为聊天页面
 */

#define MAS_SHORTHAND_GLOBALS
//意思是使用mas_equalTo时可以省去mas 变为equalTo
#define MAS_SHORTHAND
//注意:只是加上宏,能省略掉mas_,以后使用mas_makeConstraints就可以用makeConstraints


#import "ChatConversationViewController.h"
#import "Masonry.h"
#import "UIButton+Extension.h"
#import "ReceiveTableViewCell.h"
#import "SendMessageTableViewCell.h"


@interface ChatConversationViewController ()<UITextViewDelegate,UITableViewDataSource,UITableViewDelegate,EMChatManagerDelegate>

@property(nonatomic,retain)UIView *BottomView;
@property(nonatomic,retain)UIButton *talkButton;//语音按钮
@property(nonatomic,retain)UITextView *InputTextView;//输入框
@property(nonatomic,retain)UIButton *lookButton;//表情按钮
@property(nonatomic,retain)UIButton *AddButton;//添加按钮
@property(nonatomic,retain)UITableView *myTableView;
//会话类
@property (nonatomic, retain) EMConversation * conversation;

@property(nonatomic,retain)NSMutableArray *dataSources;//数据源

//计算cell高度的工具对象
@property(nonatomic,retain)ReceiveTableViewCell *RECellTool;
@property(nonatomic,retain)SendMessageTableViewCell *SendCellTool;

@end

@implementation ChatConversationViewController

-(void)dealloc{

    [super dealloc];
    [_BottomView release];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[EaseMob sharedInstance].chatManager removeDelegate:self];

    
}
////懒加载
//-(NSMutableArray *)dataSources{
//
//    if (!_dataSources) {
//        _dataSources = [NSMutableArray array];
//    }
//    return _dataSources;
//
//}

-(void)viewWillAppear:(BOOL)animated{


    [self scrollToBottom];
    [self.myTableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.dataSources = [NSMutableArray array];
    
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    //修改导航栏标题的颜色 和 大小
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],
                                                                      
                                                                      NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 46) style:UITableViewStylePlain];
  //  self.myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.myTableView.backgroundColor = [UIColor colorWithRed:220 / 255.0 green:255 / 255.0 blue:220 / 255.0 alpha:1.0];
  //  self.myTableView.backgroundColor = [UIColor whiteColor];
//    UINib *nib = [UINib nibWithNibName:@"ReceiveTableViewCell" bundle:[NSBundle mainBundle]];
//    [self.myTableView registerNib:nib forCellReuseIdentifier:@"reuse"];
    [self.view addSubview:self.myTableView];
    
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    
    [self.myTableView registerClass:[ReceiveTableViewCell class] forCellReuseIdentifier:@"reuse"];
    [self.myTableView registerClass:[SendMessageTableViewCell class] forCellReuseIdentifier:@"reuse1"];
    
    //给tableview加一个手势  负责轻拍回收键盘
    UITapGestureRecognizer *tableViewGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(commentTableViewTouchInSide)];
    tableViewGesture.numberOfTapsRequired = 1;
    tableViewGesture.cancelsTouchesInView = NO;
    [self.myTableView addGestureRecognizer:tableViewGesture];


    
    
   
    self.BottomView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 46, self.view.frame.size.width, 46)];
    self.BottomView.backgroundColor = [UIColor colorWithRed:135 / 255.0 green:206 / 255.0 blue:250 / 255.0 alpha:1.0];
    [self.view addSubview:self.BottomView];
    [_BottomView release];
    // Do any additional setup after loading the view.
    
    self.talkButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.talkButton setImage:[UIImage imageNamed:@"yuyin"] forState:UIControlStateNormal];
    [self.talkButton addTarget:self action:@selector(talkButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.BottomView addSubview:self.talkButton];
    
    self.InputTextView = [[UITextView alloc] init];
    self.InputTextView.backgroundColor = [UIColor whiteColor];
    self.InputTextView.delegate = self;
    //修改return键改为send
    self.InputTextView.returnKeyType = UIReturnKeySend;
    [self.BottomView addSubview:self.InputTextView];
    
    self.lookButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.lookButton setImage:[UIImage imageNamed:@"biaoqing"] forState:UIControlStateNormal];
        [self.lookButton addTarget:self action:@selector(lookButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.BottomView addSubview:self.lookButton];
    
    self.AddButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.AddButton setImage:[UIImage imageNamed:@"jiahao"] forState:UIControlStateNormal];
        [self.AddButton addTarget:self action:@selector(AddButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.BottomView addSubview:self.AddButton];
    

    
    
//masonry约束下方view
    [self.BottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(0);
        make.right.equalTo(0);
        make.bottom.equalTo(0);
//        make.width.equalTo(self.view);
        make.height.equalTo(46);
        
    }];
    
    //masonry约束tableview
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(0);
        make.left.equalTo(0);
        make.right.equalTo(0);
//        make.width.equalTo(self.view.frame.size.width);
//        make.height.equalTo(self.view.frame.size.height).offset(-46);
        make.bottom.equalTo(self.view).offset(-46);
        
    }];
    
    //masonry约束bottomview上的控件
    
    [self.talkButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(8);
        make.left.equalTo(10);
        make.bottom.equalTo(-10);
        make.width.height.equalTo(30);
        
        
    }];
    
    [self.InputTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.talkButton.right).offset(10);
        make.top.equalTo(5);
        make.bottom.equalTo(-5);
        make.height.equalTo(36);
        make.right.equalTo(self.lookButton.left).offset(-10);
        
    }];
    
    [self.lookButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(10);
        make.width.height.equalTo(26);
        make.right.equalTo(self.AddButton.left).offset(-10);
        make.left.equalTo(self.InputTextView.right).offset(10);
        
        
    }];
    
    [self.AddButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(8);
        make.bottom.equalTo(-8);
        make.right.equalTo(-10);
        make.width.height.equalTo(30);
        make.left.equalTo(self.lookButton.right).offset(10);
        
    }];
    
    
    //给计算高度的对象赋值
    self.RECellTool = [self.myTableView dequeueReusableCellWithIdentifier:@"reuse"];
    self.SendCellTool = [self.myTableView dequeueReusableCellWithIdentifier:@"reuse1"];
    
    //显示好友名字
    self.navigationItem.title = self.buddy.username;
    
    //加载本地数据库的聊天记录(messageV1 表)
    [self loadLocalChatMessage];
    
    // 设置聊天管理器的代理
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];;
    
    
    //1.监听键盘的弹出 self.BottomView往上移
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kbWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    //2.监听键盘退出  self.bottomView回复原位
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kbWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    
   
}
-(void)loadLocalChatMessage
{

    //获取本地聊天记录 用会话对象
  EMConversation *conversation =  [[EaseMob sharedInstance].chatManager conversationForChatter:self.buddy.username conversationType:eConversationTypeChat];
    //加载与当前用户聊天的所有记录
    NSArray *message = [conversation loadAllMessages];
 //   NSLog(@"+_++_+%@",message);
//    for (id obj in message) {
//        NSLog(@"%@",[obj class]);
//    }
    [self.dataSources addObjectsFromArray:message];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    EMMessage *message = [self.conversation.loadAllMessages objectAtIndex:indexPath.row];
    EMTextMessageBody *body = [message.messageBodies lastObject];
    
  //  CGFloat height = [ReceiveTableViewCell heightForCell:body.text];

//    ReceiveTableViewCell *cell = [ReceiveTableViewCell new];
    //计算文字高度
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:18],NSFontAttributeName, nil];
    //这里的宽度一定要和我们要显示文字的label的宽度一样
    CGRect rect = [body.text boundingRectWithSize:CGSizeMake(self.view.frame.size.width, 0) options: NSStringDrawingUsesLineFragmentOrigin  attributes:dic context:nil];
    
  //  NSLog(@"++++++++%@",  cell.myLabel.text);
    //rect.size.height 这就是文字的高度
    
    return  70 + rect.size.height;
   // return 200;

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSources.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   //1.先获取消息模型 里面有from和to的属性
    EMMessage *message = self.dataSources[indexPath.row];
   
    if ([message.from isEqualToString:self.buddy.username]) {//接收方
        ReceiveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
        
        
        cell.message = message;
        // cell.backgroundColor = [UIColor colorWithRed:220 / 255.0 green:255 / 255.0 blue:220 / 255.0 alpha:1.0];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {//发送方
        SendMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse1" forIndexPath:indexPath];
        cell.message = message;
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    
    
//    
//    if (indexPath.row % 2 == 0) {
// 
//    }
//    else{
//    
//     
//    
//    }

    
}



//键盘显示时会触发的方法
-(void)kbWillShow:(NSNotification *)noti{

//1.获取键盘高度 (键盘结束时位置)
    CGRect kbEndFrame = [noti.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
  //  NSLog(@"++++++++%f",kbEndFrame.origin.y);
    CGFloat kbHeight = kbEndFrame.size.height;
  //  CGFloat kbHeight2 = self.view.frame.size.height - (kbHeight + 46);
    //2.更改底部约束

    [self.BottomView mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.equalTo(self.view.bottom).offset(-kbHeight);
        
    }];
    
    [self.myTableView mas_updateConstraints:^(MASConstraintMaker *make) {
        
       
        make.bottom.equalTo(self.view.bottom).offset(-kbHeight - 46);
       // make.height.equalTo(kbHeight2);
        
    }];

    //添加一个动画
    [UIView animateWithDuration:0.25 animations:^{
        
        [self.view layoutIfNeeded];
    }];
    

}

-(void)kbWillHide:(NSNotification *)noti{
 
    //1.获取键盘高度 (键盘结束时位置)
    //  NSLog(@"++++++++%f",kbEndFrame.origin.y);
    //2.更改底部约束

    [self.BottomView mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.equalTo(0);
        
    }];
    
    [self.myTableView mas_updateConstraints:^(MASConstraintMaker *make) {
        
      //  make.height.equalTo(self.view).offset(-46);
        make.bottom.equalTo(self.view).offset(-46);
    }];
    
    //添加一个动画
//    [UIView animateWithDuration:0.25 animations:^{
    
        [self.BottomView layoutIfNeeded];
//    }];



}

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event

{
    
    //隐藏键盘
    
    [self.InputTextView resignFirstResponder];
    
}

-(void)talkButtonAction{

    NSLog(@"我是切换语音按钮");

}

-(void)lookButtonAction{

    NSLog(@"我是表情按钮");

}

-(void)AddButtonAction{

    NSLog(@"我是添加按钮");

}

//uitextview代理
-(void)textViewDidChange:(UITextView *)textView{

    NSLog(@"%@",textView.text);
    //监听send事件 判断有没有换行
    if ([textView.text hasSuffix:@"\n"]) {
        NSLog(@"发送");
        [self sendMessage:textView.text];
        
        //清空textview的文字
        textView.text = nil;
    }
    

}

-(void)sendMessage:(NSString *)text{

    //消息 = 消息头 + 消息体
    
    //创建消息体
   // EMTextMessageBody   文本消息体
   // EMVoiceMessageBody  录音消息体
  //  EMVideoMessageBody  视频消息体
  //  EMLocationMessageBody 位置消息体
  //  EMImageMessageBody   图片消息体
    
    NSLog(@"要发送给  %@",self.buddy.username); 
   // return;
    //创建一个聊天文本对象
    EMChatText *chattext = [[EMChatText alloc] initWithText:text];
    
    //创建一个文本消息体
    
    EMTextMessageBody *textBody = [[EMTextMessageBody alloc] initWithChatObject:chattext];
    
    //1.创建消息对象
    EMMessage *messageOBj = [[EMMessage alloc] initWithReceiver:self.buddy.username bodies:@[textBody]];
    
//    消息类型
//    @constant eMessageTypeChat            单聊消息(默认)
//    @constant eMessageTypeGroupChat       群聊消息
//    @constant eMessageTypeChatRoom        聊天室消息
    
    messageOBj.messageType = eMessageTypeChat;
    
    //2.发送消息
    [[EaseMob sharedInstance].chatManager asyncSendMessage:messageOBj progress:nil prepare:^(EMMessage *message, EMError *error) {
        
        NSLog(@"准备发送消息");
    } onQueue:nil completion:^(EMMessage *message, EMError *error) {
        
        NSLog(@"完成消息发送 %@",error);
    } onQueue:nil];

//3.把消息添加到数据源 刷新
    [self.dataSources addObject:messageOBj];
    [self.myTableView reloadData];
    
    //4.把消息显示在顶部
    [self scrollToBottom];

}

#pragma mark - 接收好友的回复消息
-(void)didReceiveMessage:(EMMessage *)message{

    //一定要判断是当前的聊天用户 才能加到数据源
    if ([message.from isEqualToString:self.buddy.username]) {
        //1.把接收的消息添加到数据源
        [self.dataSources addObject:message];
        
        //2.刷新表格
        [self.myTableView reloadData];
        
        //3.显示
        [self scrollToBottom];

    }
    
  
}



//滑动tableview时回收键盘
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.InputTextView resignFirstResponder];
    
}

-(void)commentTableViewTouchInSide{

    [self.InputTextView resignFirstResponder];

}


-(void)scrollToBottom{
    
    //获取最后一行
    if (self.dataSources.count == 0) {
        return;
    }
    NSIndexPath *lastPath = [NSIndexPath indexPathForRow:self.dataSources.count - 1 inSection:0];
    
    [self.myTableView scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];



}

@end
